from pathlib import Path
from typing import Optional
from dataclasses import dataclass
from .xdb_searcher import XdbSearcher

root_path = Path(__file__).parent
db_path = root_path / "data" / "ip2region.xdb"


@dataclass
class IpInfo:
    country: Optional[str]
    region: Optional[str]
    city: Optional[str]


class Ip2Region:
    def __init__(self):
        cb = XdbSearcher.loadContentFromFile(dbfile=db_path)
        self.searcher = XdbSearcher(contentBuff=cb)

    def search(self, ip: str) -> IpInfo:
        res = self.searcher.search(ip)
        res_array = res.split("|") if res else []

        # 处理空值情况，将"0"转换为None
        def clean_value(value: str) -> Optional[str]:
            return None if not value or value == "0" else value

        # 确保至少有5个元素，不足的用空字符串补充
        while len(res_array) < 5:
            res_array.append("")

        # 解析各个字段
        country = clean_value(res_array[0])  # 国家
        region = clean_value(res_array[2])  # 省份
        city = clean_value(res_array[3])  # 城市

        return IpInfo(country=country, region=region, city=city)


searcher = Ip2Region()
